/* 
 构建以后重写 serverWorker 配置，
 
 

*/



import path from 'path'
import { fileURLToPath } from 'url'
const __filenameNew = fileURLToPath(import.meta.url);
const __dirnameNew = path.dirname(__filenameNew);
import md5 from 'md5';
import { Hash } from 'crypto';
import { rename, readFile, readFileSync, writeFileSync, promises, mkdirSync } from "fs";

import { exec, execSync } from 'child_process';

let timeStmipHash=Hash('sha1').update(new Date().getTime()+'').digest('hex').slice(0, 10);;
const globalConfig = {
    publishAuthor: "",
    publishTime:""
}


/**
 * creatSetCacheFileConfig对象用于配置缓存文件的创建。
 * 
 * @property {string} targetFileName 目标文件名称。
 * @property {string} targetFilePath 目标文件路径。
 * @property {string} sourceFileName 源文件名称。
 * @property {string} sourceFilePath 源文件路径。
 * @property {string} fileHash 文件的哈希值，用于校验文件是否被修改。
 */
let creatSetCacheFileConfig = {
    targetFileName: 'rewriteCacheStorage.js', // 目标文件名
    targetFilePath: ``, // 目标文件路径，初始化为空
    sourceFileName: "setCaches.js", // 源文件名
    sourceFilePath: ``, // 源文件路径，初始化为空
    fileHash: '' // 文件哈希值，初始化为空
}

// 设置目标文件的完整路径
creatSetCacheFileConfig.targetFilePath = `${__dirnameNew}/dist/${creatSetCacheFileConfig.targetFileName}`;

// 设置源文件的完整路径
creatSetCacheFileConfig.sourceFilePath = `${__dirnameNew}/${creatSetCacheFileConfig.sourceFileName}`;

 
/**
 * 定义一个对象用于配置写入文件的操作。
 * 
 * @property {string} targetFileName 目标文件名。
 * @property {string} targetFilePath 目标文件的完整路径。
 * @property {string} sourceFileName 源文件名。
 * @property {string} sourceFilePath 源文件的完整路径。
 * @property {string} fileHash 文件的哈希值。
 */
let writeFileSetWorkBoxConfig = {
    targetFileName: 'workbox-f3e6b16a.js', // 目标文件名
    targetFilePath: ``, // 目标文件路径，初始化为空
    sourceFileName: "setWorkbox.js", // 源文件名
    sourceFilePath: ``, // 源文件路径，初始化为空
    fileHash: '' // 文件哈希值，初始化为空
}

// 设置目标文件的完整路径
writeFileSetWorkBoxConfig.targetFilePath = `${__dirnameNew}/dist/${writeFileSetWorkBoxConfig.targetFileName}`;

// 设置源文件的完整路径
writeFileSetWorkBoxConfig.sourceFilePath = `${__dirnameNew}/${writeFileSetWorkBoxConfig.sourceFileName}`;




var precacheAndRoute = [
    {
        url: "assets/js/elementPlusModules.js",
        revision: null
    },
    {
        url: "assets/js/piniaModules.js",
        revision: null
    },
    // {
    //     url: "assets/js/axiosModules.js",
    //     revision: null
    // },
    {
        url: "assets/js/vueRouterModules.js",
        revision: null
    },
    {
        url: "assets/js/dayjsModules.js",
        revision: null
    },
    {
        url: "assets/js/echartsModules.js",
        revision: null
    },
    {
        url: "assets/js/sortablejsModules.js",
        revision: null
    },
    {
        url: "assets/js/lodashModules.js",
        revision: null
    },
    {
        url: "assets/js/prismjsModules.js",
        revision: null
    },
    {
        url: "assets/js/cryptoJsModules.js",
        revision: null
    }

]

precacheAndRoute = [];
const v = Math.round(Math.random() * new Date().getTime())
// console.log(rename)
let filePath = __dirnameNew + '/dist/assets/';

const renameFileInDir = async (dirPath, reNameFun) => {
    console.log(dirPath)
    // const entries=await promises.readdir(dirPath);
    const entries = await promises.readdir(dirPath, { withFileTypes: true });


    // console.log(entries)
    for (let entry of entries) {

        if (entry.isDirectory()) {
            let childrenFilePath = dirPath + entry.name;
            renameFileInDir(childrenFilePath, reNameFun)

        } else {
            const orgFilePath = path.join(dirPath, entry.name);


            if (entry.name) {
                writeSw(orgFilePath)
            }

        }

    }


}
const renameFn = (fileName) => {
    return fileName.split("?")[0];
}

// renameFileInDir(filePath, renameFn)

const writeSw = (reWritefilePath) => {
    console.log(reWritefilePath)
    let jsReg = /(_v_(js|css|gif|png|jpg|webp|doc|pdf|html]))([0-9a-zA-z]{0,})(\.(js|css|gif|png|jpg|webp|doc|pdf|html]))/ig;
    let r = Math.round(Math.random() * new Date().getTime());
    // let filePath = __dirnameNew + '/dist/sw.js';
    let file = readFileSync(reWritefilePath, 'utf-8');
    file = file.replaceAll(jsReg, (a, b, c, d) => {
        return `${a}?r=${v}`;

    });

    writeFileSync(reWritefilePath, file);
}

//重写workBox内容
const writeFileSetWorkBox = () => {
    let distWorkBoxPath = writeFileSetWorkBoxConfig.targetFilePath;
    let path =  writeFileSetWorkBoxConfig.sourceFilePath;
    let content = readFileSync(path, 'utf8');
    writeFileSync(distWorkBoxPath, content);
    console.log("写入workbox-f3e6b16a.js文件成功！")
}
writeFileSetWorkBox()



//写入缓存文件设置代码
const writeSetCacheFile = () => {
    let targetPath = creatSetCacheFileConfig.targetFilePath;
    let setcacheScourPath = creatSetCacheFileConfig.sourceFilePath;
    let content =   readFileSync(setcacheScourPath, 'utf8');
    content=`let timeStmip =${new Date().getTime()};`+content;
    writeFileSync(targetPath, content);
 
    creatSetCacheFileConfig.fileHash = timeStmipHash
    console.log('写入浏览器cacheStorage控制程序文件成功！')
 
}
writeSetCacheFile()


//读取当前 git信息
const readGitInfo = () => {
    let d=new Date();
    let gitInfo = execSync('git config --global user.name').toString();
    globalConfig.publishAuthor = gitInfo;
    const dateFormat=(num)=>{ 
        return num<10?'0'+num:num;
    }
   let  dataar={
        Year:d.getFullYear(),
        Month:dateFormat(d.getMonth()+1),
        Day:dateFormat(d.getDate()),
        Hour:dateFormat(d.getHours()),
        Minute:dateFormat(d.getMinutes()),
        Second:dateFormat(d.getSeconds()),
    }

    globalConfig.publishTime=`${dataar.Year}-${dataar.Month}-${dataar.Day} ${dataar.Hour}:${dataar.Minute}:${dataar.Second}`;
  
}
readGitInfo();

const writeSwjs = (reWritefilePath) => {

    let path = __dirnameNew + '/dist/sw.js';

    const content = `if (!self.define) {let s, e = {};const l = (l, i) => (l = new URL(l + ".js", i).href, e[l] || new Promise((e => {if ("document" in self){
             const s = document.createElement("script");
                s.src = l, s.onload = e, document.head.appendChild(s)
            } else s = l, importScripts(l), e()
        })).then((() => {
            let s = e[l];
            if (!s) throw new Error("Module  didn’t register its module");
            return s
        })));
        self.define = (i, n) => {
            const r = s || ("document" in self ? document.currentScript.src : "") || location.href;
            if (e[r]) return;
            let u = {};
            const t = s => l(s, r),
                a = {
                    module: {
                        uri: r
                    },
                    exports: u,
                    require: t
                };
            e[r] = Promise.all(i.map((s => a[s] || t(s)))).then((s => (n(...s), u)))
        }
    }
    define(["./workbox-f3e6b16a"], (function(s) {
        "use strict";
        self.skipWaiting(), s.clientsClaim(), s.precacheAndRoute(${JSON.stringify(precacheAndRoute)}, {}), s.cleanupOutdatedCaches(), s.registerRoute(new s.NavigationRoute(s.createHandlerBoundToURL(
            "index.html")))
    }));`
    // let file = readFileSync(path, 'utf-8');

    // file = file.replace(/\{url:"index.html"\,revision:"[a-z0-9A-Z_-]{0,}"\}\,/ig, '')

    writeFileSync(path, content);
}
// writeSwjs()//  暂时关闭重写 sw文件，缓存所有文件

const writeRegSwjs = (reWritefilePath) => {

    let path = __dirnameNew + '/dist/registerSW.js';
    const content = `
    if ('serviceWorker' in navigator) {
        let newWorkerId="${new Date().getTime()}"
        window.addEventListener('load',
         () => {
               
                   navigator.serviceWorker.ready.then(registration => {
                            registration.unregister();
                          }); 
                        //   registration.unregister();
               //  navigator.serviceWorker.register('/sw.js?v=${new Date().getTime()}', { scope: '/' })
                
            })
    }
    `

    writeFileSync(path, content);
}
writeRegSwjs()



//重写index.html
const writeIndexHTML = (reWritefilePath) => {
  
    let path = __dirnameNew + '/dist/index.html';  
    let content = readFileSync(path, 'utf-8');
    let setCachesScript = `<script  crossorigin src="/rewriteCacheStorage.js?v=${timeStmipHash}"></script>`
    content = content.replace('registerSW.js', `registerSW.js?v=${timeStmipHash}`);
    content = content.replace('</head>', setCachesScript + '</head>'); 
    content += `<!-- 最近一次发布时间:${globalConfig.publishTime} ; 发布人:${globalConfig.publishAuthor}-->`
    writeFileSync(path, content);
    console.log("写入index.html 文件成功！")
    console.log(`发布人:${globalConfig.publishAuthor.replace(/[\r\n]/g, '')}`)
    console.log(`发布时间:${globalConfig.publishTime}`)
}
writeIndexHTML()
// writeSw()



